<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\h5;

use app\wework\controller\Base;
use app\wework\model\BaseModel;
use app\wework\model\Helper;
use app\wework\model\QyWechatApi;
use think\facade\Db;
use app\wework\model\JsSdk;
use think\facade\Log;
use think\facade\View;

/**
  * 客户画像
 */
class CustomerPortrait extends Base
{
	public function index(){
		$code = $this->req->param("code");
		$wid = $this->req->param("wid");
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		$wid = $config["wid"];
		if($code){
			$resArr = QyWechatApi::getuserinfo($wid,$code);
			$jsSdkServe = new JsSdk($config["corp_id"],$wid);
			$wxConfig = $jsSdkServe->getSignPackage();
			$agentConfig = $jsSdkServe->getSignPackage('','agent');
			$where["wid"] = $wid;
			$where["userid"] = $resArr["UserId"];
			$staff = Helper::getUser($where);
			if(!$staff)return error("请先同步通讯录成员");
			View::assign("corp_id", $config["corp_id"]);
			View::assign("agent_id", $selfapp["agent_id"]);
			View::assign("wxConfig", $wxConfig);
			View::assign("agentConfig", $agentConfig);
			View::assign("wid", $wid);
			View::assign("staff_id", $staff["id"]);
			return view();
		}else{
			$redirect_uri = urlencode($this->req->domain().'/wework/h5.CustomerPortrait/index.html?wid='.$wid);
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config["corp_id"].'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
			return redirect($url);
		}
	}

	public function customer_info(){
		$addWay = addWay();
		//客户详情
		$wid = $this->req->param("wid");
		$external_userid = $this->req->param("external_userid");
		$staff_id = $this->req->param("staff_id");
		$wheres["wid"] = $wid;
		$wheres["staff_id"] = $staff_id;
		$wheres["external_userid"] = $external_userid;
		$customer = Helper::getCustomer($wheres);
		if(!$customer)return error("未知客户");
		$customer["add_way"] =  $addWay[$customer["add_way"]];
		$customer["remark_mobiles"] = json_decode($customer["remark_mobiles"],1)?:"";
		$customer["tags"] = json_decode($customer["tags"],1);
		$tags = Db::table("kt_wework_tag")->where(["tag_id"=>$customer["tags"]])->field("tag_name")->select()->toArray();
		$customer["tags"] = array_column($tags, "tag_name");
		$customer["createtime"] = date("Y-m-d H:i:s",$customer["createtime"]);
		//客户动态
		$dynamic = Db::table("kt_wework_customer_dynamic")
					->where(["wid"=>$wid,"customer_userid"=>$external_userid])
					->filter(function($data) use($wid){
					    $data["ctime"] = date("m-d",strtotime($data["create_time"]));
					    $data["create_time"] = date("H:i",strtotime($data["create_time"]));
						if($data["staff_id"])$data["staff"] = Db::table("kt_wework_staff")->where(["wid"=>$wid,"id"=>$data["staff_id"]])->field("name,avatar")->find();
						if($data["chat_id"])$data["group_name"] = Db::table("kt_wework_group")->where(["wid"=>$wid,"chat_id"=>$data["chat_id"]])->field("name")->find()["name"]?:"默认群聊";
						if($data["type"] == 5)$data["radar"] = Db::table("kt_wework_radar")->where(["wid"=>$wid,"id"=>$data["glian_id"]])->field(["title"])->find()["title"];
						return $data;
					})
					->select()
					->toArray();
		//自定义信息
		$setfield = array_column(Db::table("kt_wework_customer_setfield")->where(["wid"=>$wid,"type"=>1,"status"=>1])->field("name")->select()->toArray(),"name");
		$setfield_list = Db::table("kt_wework_customer_setfield")
		                    ->where(["wid"=>$wid,"type"=>2,"status"=>1])
		                    ->order("sort desc")
		                    ->filter(function($data) use($wid,$staff_id,$external_userid){
		                        $setfield_data = Db::table("kt_wework_customer_setfield_data")->where(["wid"=>$wid,"pid"=>$data["id"],"external_userid"=>$external_userid,"staff_id"=>$staff_id])->find();
	                            $data["status"] = 2;
		                        if($setfield_data){
		                            $data["status"] = 1;
		                            $data["value"] = $setfield_data["content"];
		                        }
		                        return $data;
		                    })
		                    ->select()
		                    ->toArray();
		if($customer["remark_mobiles"])$customer["remark_mobiles"] = implode(",",$customer["remark_mobiles"]);
		
		View::assign("setfield_list",$setfield_list);
		View::assign("setfield",$setfield);
		View::assign("dynamics", $dynamic);
		View::assign("staff_id", $staff_id);
		View::assign("external_userid", $external_userid);
		View::assign("customer", $customer);
		return view();
	}
	
	public function upd_user_fields(){
		$id = $this->req->param("id");
		$wid = $this->req->param("wid");
		$external_userid = $this->req->param("external_userid");
		$content = $this->req->param("content");
		$staff_id = $this->req->param("staff_id");
		$setfield_data = Db::table("kt_wework_customer_setfield_data")->where(["wid"=>$wid,"pid"=>$id,"external_userid"=>$external_userid,"staff_id"=>$staff_id])->find();
		if($setfield_data)Db::table("kt_wework_customer_setfield_data")->where(["wid"=>$wid,"pid"=>$id,"external_userid"=>$external_userid,"staff_id"=>$staff_id])->update(["content"=>$content]);
		if(!$setfield_data){
		    $data["wid"] = $wid;
    		$data["pid"] = $id;
    		$data["external_userid"] = $external_userid;
    		$data["content"] = $content;
    		$data["staff_id"] = $staff_id;
    		$data["ctime"] = date("Y-m-d H:i:s");
    		Db::table("kt_wework_customer_setfield_data")->insertGetId($data);
		}
		return success("操作成功");
	}

	public function upload_user(){
		$input = $this->req->param('input');
		$name = $this->req->param('name');
		$one = $this->req->param('one');
		$id = $this->req->param('id');
		$customer = Helper::getCustomer(["id"=>$id]);
		$wid = $customer["wid"];
		$times = $customer["createtime"];
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		$data[$name] = $input;
		$external_userid = $customer["external_userid"];
		$staff = Helper::getUser(["id"=>$customer["staff_id"]]);
		if($name == "mobiles"){
			$one = "手机号";
			$mobile = explode(",", $input);
            foreach ($mobile as $key => $value) {
                if(strlen($value) != 11)return error("手机号格式错误");
            }
			$param = ['userid'=>$staff['userid'],'external_userid'=>$external_userid,'remark_mobiles'=>$mobile];
            $res = QyWechatApi::externalcontactRemark($param,$wid);
	        if($res["errmsg"] != "ok")return error("操作失败",$res["errcode"]);
        	$mobiles = json_encode(explode(",", $input),320);
			$data["remark_mobiles"] = $mobiles;
		}else if($name == "描述"){
			if($customer["description"] == $input)return error($one."未修改");
			$param = ['userid'=>$staff['userid'],'external_userid'=>$external_userid,'description'=>$input];
            $res = QyWechatApi::externalcontactRemark($param,$wid);
	        if($res["errmsg"] != "ok")return error("操作失败",$res["errcode"]);
        	$data["description"] = $input;
		}
		Db::table("kt_wework_customer")->where(["id"=>$id])->save($data);

		return success($one.'修改成功',$input);
	}

	public function staff(){
		$wid = $this->req->param("wid");
		$code = $this->req->param("code");
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		$wid = $config["wid"];
		if($code){
			$user_ticket = QyWechatApi::getUserTicket($wid,$code);
		    if($user_ticket["errcode"] !== 0)return error("接口错误",$user_ticket["errcode"]);
		    $data = [
				'user_ticket' => $user_ticket["user_ticket"]
			];
			$staffs = QyWechatApi::getUserDetail($wid,$data);
		    if($staffs["errcode"] !== 0)return error("接口错误",$staff["errcode"]);
		    $staff = Db::table("kt_wework_staff")->where(["wid"=>$wid,"userid"=>$staffs["userid"]])->find();
		    if($staff)return error("已同步");
		    $data["wid"] = $wid;
		    $data["userid"] = $staffs["userid"];
		    $data["mobile"] = $staffs["mobile"];
		    $data["gender"] = $staffs["gender"];
		    $data["email"] = $staffs["email"];
		    $data["avatar"] = $staffs["avatar"];
		    $data["qr_code"] = $staffs["qr_code"];
		    $data["address"] = $staffs["address"];
			$res = QyWechatApi::getUserInfos($wid,$staffs["userid"]);
		    $data["name"] = $res["name"];
		    $data["is_leader_in_dept"] = $res["isleader"];
		    $data["position"] = $res["position"];
		    $data["status"] = $res["status"];
		    $data["telephone"] = $res["telephone"];
		    $data["main_department"] = $res["main_department"];
		    if(array_key_exists("external_profile",$res))$data["external_profile"] = json_encode($res["external_profile"],320);
		    if(array_key_exists("department",$res)){
		        $data["department"] = json_encode($res["department"],320);
		        $department = Db::table("kt_wework_department")->where(["wid"=>$wid,"department_id"=>$res["department"]])->field("department_name")->select()->toArray();
		        $data["department_name"] = json_encode(array_column($department,"department_name"),320);
		    }
		    $data["extattr"] = json_encode($res["extattr"],320);
		    Db::table("kt_wework_staff")->insertGetId($data);
            return success('同步成功');
		}else{
			$redirect_uri = urlencode($this->req->domain().'/wework/h5.CustomerPortrait/staff.html?wid='.$wid);
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config["corp_id"].'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_privateinfo&agentid='.$selfapp["agent_id"].'&state=STATE#wechat_redirect';
			return redirect($url);
		}
	}

	public function customer_infos(){
	    return view();
	}
}